<script setup lang="ts">
import type { TableProps } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode, ref } from 'vue'
import { cloneDeep } from 'lodash'
import PurchaseItemAdd from './components/purchase-item-add.vue'
import type { PurchaseDetailItemModel, PurchaseDetailModel } from '@/api/purchase/purchase-list.ts'
import { getPurchaseInfo } from '@/api/purchase/purchase-list.ts'

const formData = ref<PurchaseDetailModel>()

const visible = ref(false)

const purchaseItemAdd = ref<InstanceType<typeof PurchaseItemAdd>>()

async function handleAdd() {
  console.log('当前打开时使用的采购单号是：', formData.value?.purchaseId)
  const purchaseItem = ref<PurchaseDetailItemModel>({
    purchaseId: formData.value?.purchaseId,
    quantity: 0, // 斤数
    price: 0, // 单价
    totalPrice: 0,
    actualAmount: 0,
    itemDate: undefined,
    itemType: 1,
    settlementStatus: 1,
    settlementAmount: 0,
    irSettlementAmount: 0,
  })
  console.log(purchaseItem)
  purchaseItemAdd.value?.open(purchaseItem.value)
}

async function handleEdit(record: PurchaseDetailItemModel) {
  purchaseItemAdd.value?.open(record)
}

function open(record?: PurchaseDetailModel) {
  console.log('进入open方法')
  console.log(record?.purchaseId)
  visible.value = true
  formData.value = cloneDeep(record)
  getItemsList()
}

const dataSource = ref<PurchaseDetailItemModel[]>([])

const pagination = ref({
  pageSize: 5,
  pageSizeOptions: ['10', '20', '30', '40', '50'],
  showQuickJumper: true,
  total: 0,
})

// 获取采购单信息详情
async function getItemsList() {
  const reqForm = ref<PurchaseDetailModel>({
    purchaseId: formData.value?.purchaseId,
  })
  const { data } = await getPurchaseInfo(reqForm.value)
  formData.value = data
  dataSource.value = data?.items
  pagination.value.total = data?.items.length ?? 0
  console.log(dataSource.value)
}

/*
  处理删除对话框
*/
function showConfirm(index: PurchaseDetailItemModel) {
  Modal.confirm({
    title: '删除任务',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { }, '确定要删除该任务吗?'),
    cancelText: '取消',
    okText: '确认',
    onOk() {
      dataSource.value.splice(index.itemId, 1)
    },
    class: 'test',
  })
}

/*onMounted(() => {
  getItemsList()
})*/

function onClose() {
  visible.value = false
  console.log('关闭，准备刷新列表')
}

function onAfterOpenChange() {
  // console.log('加载动画结束')
}

function purchaseDetailItemSave() {
  // 刷新子级列表
}

const loading = shallowRef(false)

const columns = shallowRef([
  {
    title: '明细编号',
    dataIndex: 'itemId',
    width: 70,
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
  },
  {
    title: '数量，斤数',
    dataIndex: 'quantity',
  },
  {
    title: '采购单价',
    dataIndex: 'price',
  },
  {
    title: '采购自动总价',
    dataIndex: 'totalPrice',
  },
  {
    title: '关联客户名称',
    dataIndex: 'customerName',
  },
  {
    title: '采购实际总价',
    dataIndex: 'actualAmount',
  },
  {
    title: '采购日期',
    dataIndex: 'itemDate',
  },
  {
    title: '已结算金额',
    dataIndex: 'settlementAmount',
  },
  {
    title: '剩余结算金额',
    dataIndex: 'irSettlementAmount',
  },
  {
    title: '采购状态',
    dataIndex: 'itemType',
  },
  {
    title: '结算状态',
    dataIndex: 'settlementStatus',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 100,
  },
])

const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}


const tableSize = ref<string[]>(['large'])


const settlementStatusMap = {
  1: '已结算',
  2: '未结算',
  3: '部分结算',
}

const itemTypeMap = {
  1: '正常采购',
  2: '全额抵消',
  3: '部分抵消',
}

defineExpose({
  open,
})
</script>

<template>
  <a-drawer v-model:open="visible" width="1200px" title="采购单详情" @close="onClose" @afterOpenChange="onAfterOpenChange">
    <!-- 头部 -->
    <a-card>
      <a-row :gutter="16">
        <a-descriptions title="采购单信息">
          <a-descriptions-item label="采购单号">
            {{ formData?.purchaseId }}
          </a-descriptions-item>
          <a-descriptions-item label="采购人">
            {{ formData?.purchaseUser }}
          </a-descriptions-item>
          <a-descriptions-item label="运费总价">
            ￥ {{ formData?.purchaseFreight }}
          </a-descriptions-item>
          <a-descriptions-item label="实际采购总金额">
            ￥ {{ formData?.purchaseActualAmount }}
          </a-descriptions-item>
          <a-descriptions-item label="采购单描述">
            {{ formData?.purchaseDescribe }}
          </a-descriptions-item>
          <a-statistic title="采购自动总价" :precision="2" :value="formData?.purchaseTotalPrice" />
          <a-descriptions-item label="采购车辆">
            {{ formData?.purchaseVehicle }}
          </a-descriptions-item>
          <a-descriptions-item label="采购状态">
            {{ itemTypeMap[formData?.purchaseStatus as keyof typeof itemTypeMap] as string }}
          </a-descriptions-item>
          <a-descriptions-item label="采购单付款状态">
            {{ settlementStatusMap[formData?.purchasePaymentStatus as keyof typeof settlementStatusMap] as string }}
          </a-descriptions-item>
          <a-descriptions-item label="成本单价">
            ￥ {{ formData?.purchaseUnitCost }}
          </a-descriptions-item>
          <a-descriptions-item label="采购总斤数">
            {{ formData?.purchaseTotal }}
          </a-descriptions-item>
          <a-descriptions-item label="剩余结算总金额">
            ￥ {{ formData?.remainSettlementAmount }}
          </a-descriptions-item>
          <a-descriptions-item label="采购发车日期">
            {{ formData?.purchaseDeparture }}
          </a-descriptions-item>
        </a-descriptions>
      </a-row>
    </a-card>

    <!-- 列表 -->
    <a-card class="mt-5">
      <template #title>
        <!-- 底部添加按钮 -->
        <a-button type="dashed" @click="handleAdd()">
          + 添加新采购明细
        </a-button>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="showConfirm(scope?.record as PurchaseDetailItemModel)">
                作废
              </a>
              <a @click="handleEdit(scope?.record as PurchaseDetailItemModel)">
                编辑
              </a>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'settlementStatus'">
            <div gap-2>
              {{ settlementStatusMap[scope?.record?.settlementStatus as keyof typeof settlementStatusMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'itemType'">
            <div gap-2>
              {{ itemTypeMap[scope?.record?.itemType as keyof typeof itemTypeMap] as string }}
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 采购明细添加 -->
    <PurchaseItemAdd ref="purchaseItemAdd" @purchaseDetailItemSave="purchaseDetailItemSave"></PurchaseItemAdd>
  </a-drawer>
</template>

<style>
.a-extra {
  display: flex;
  align-items: center;
  justify-content: end;
}
</style>
